package com.ljp.pc.object;

import java.util.Queue;
import java.util.Random;

public class Producer implements Runnable {
    private final Queue<Integer> queue;
    private int maxSize;
    volatile Integer offerValue = 0;

    public Producer(Queue<Integer> queue, int maxSize) {
        this.queue = queue;
        this.maxSize = maxSize;
    }

    @Override
    public void run() {

        while (true) {
            synchronized (queue) {
                while (queue.size() >= maxSize) {
                    System.out.println("队列已满，生产者(" + Thread.currentThread().getName() + ")等待消费者消费");
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("生产者(" + Thread.currentThread().getName() + ")生产，值为：" + offerValue);
                queue.offer(offerValue);
                offerValue++;
                queue.notifyAll();
                try {
                    //随机生产
                    Thread.sleep(new Random().nextInt(10000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
